package admin

import (
	"MembershipRegist/db"
	"MembershipRegist/models"
)

func (c *Controller) Users() {
	var users []models.User
	offset := c.GetString("offset")
	limit := c.GetString("limit")
	// 不分页
	if limit == "" || limit == "0" {
		db.DB.Order("id desc").Find(&users)
	} else {
		db.DB.Limit(limit).Offset(offset).Order("id desc").Find(&users)
	}

	var total int
	db.DB.Model(&models.User{}).Count(&total)
	result := make(map[string]interface{})
	result["status"] = 200
	result["message"] = "success"
	result["total"] = total
	result["users"] = users
	c.Data["json"] = result
	c.ServeJSON()
}

func (c *Controller) UserDelete() {
	userID, err := c.GetInt("user_id")
	if err != nil {
		c.ResponseFailed(201, "user_id 不合法")
		return
	}

	if value := db.DB.Unscoped().Delete(&models.User{}, "id = ?", userID); value.Error != nil {
		c.ResponseFailed(202, "删除用户失败")
		return
	}

	c.ResponseSuccess()
}

func (c *Controller) UserQuery() {
	username := c.GetString("username")
	var users []models.User
	db.DB.Where("username like ?", "%"+username+"%").Find(&users)
	result := make(map[string]interface{})
	result["status"] = 200
	result["message"] = "success"
	result["users"] = users
	c.Data["json"] = result
	c.ServeJSON()
}

func (c *Controller) UserUpdate() {
	userID, err := c.GetInt("user_id")
	if err != nil {
		c.ResponseFailed(201, "user_id 不合法")
		return
	}

	password := c.GetString("password")
	nickname := c.GetString("nickname")
	studentID := c.GetString("student_id")
	updateValue := make(map[string]interface{})
	if password != "" {
		updateValue["password"] = password
	}
	if nickname != "" {
		updateValue["nickname"] = nickname
	}
	if studentID != "" {
		updateValue["student_id"] = studentID
	}

	db.DB.Model(&models.User{}).Where("id = ?", userID).Updates(updateValue)

	c.ResponseSuccess()
}
